# -*- coding: utf-8 -*-

# graphic-pppoe-client - Easy graphic networking manager
#
# Author: GoTLiuM InSPiRiT <gotlium@gmail.com>
#
# Copyright 2010, GoTLiuM InSPiRiT <gotlium@gmail.com>.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.

from subprocess import Popen, STDOUT, PIPE
from sys import platform, maxsize
from os import getuid, kill
from libraries.fs import getFile, fileExists
from ctypes import CDLL
from math import log

def system(command, as_text = False):
	try:
		if not command: return None
		p = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT)
		result = p.communicate()[0].strip()
		if not result:
			return None
		elif as_text:
			return result
		else:
			return result.split("\n")
	except:
		return None

def isLinux():
	if platform.find('linux') != -1:
		return True
	return False

def isRoot():
	return getuid() == 0

def isRunned(pid_file):
	pid = getFile(pid_file)
	if pid:
		try:
			kill(int(pid), 0)
			return True
		except:
			pass
	return False

def renameProcess(name, libc = None):
	try:
		if int(log(maxsize, 2)) == 63:
			libc = '/lib/x86_64-linux-gnu/libc.so.6'
			if not fileExists(libc):
				libc = '/lib64/libc.so.6'
				if not fileExists(libc):
					libc = '/lib/libc.so.6'
		else:
			libc = '/lib/i386-linux-gnu/libc.so.6'
			if not fileExists(libc):
				libc = '/lib32/libc.so.6'
				if not fileExists(libc):
					libc = '/lib/libc.so.6'
		if libc:
			CDLL(libc).prctl(15, name, 0, 0, 0)
			return True
	except:
		pass
	return False

def msg(message):
	print("> %s" % str(message))
